import 'package:flutter/material.dart';

// 通过GlobalKey局部刷新
/// https://www.jianshu.com/p/7765d8605864?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin
class BlockRefreshWithGlobalkey extends StatefulWidget {
  const BlockRefreshWithGlobalkey({Key? key}) : super(key: key);

  @override
  _BlockRefreshWithGlobalkeyState createState() =>
      _BlockRefreshWithGlobalkeyState();
}

class _BlockRefreshWithGlobalkeyState extends State<BlockRefreshWithGlobalkey> {
  int currentIndex = 0;

  // globalkey唯一定义了某个element，它使你能够访问与element相关联的其他对象，例如buildContext、state等。应用场景：跨widget访问状态。
  GlobalKey<_RightMenuState> _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Refreshable局部刷新"),
          centerTitle: true,
        ),
        body: Container(
          child: Row(
            children: [
              Container(
                  color: Colors.grey,
                  width: 100,
                  child: LeftMenuWidget((index) {
                    _globalKey.currentState!.changePos(index);
                  })),
              Expanded(child: RightMenu(_globalKey))
            ],
          ),
        ),
      ),
    );
  }

  void onPositionChanged(int newIndex) {
    setState(() {
      currentIndex = newIndex;
    });
  }
}

class LeftMenuWidget extends StatefulWidget {
  final Function(int index) callback;

  const LeftMenuWidget(this.callback, {Key? key}) : super(key: key);

  @override
  _LeftMenuWidgetState createState() => _LeftMenuWidgetState();
}

class _LeftMenuWidgetState extends State<LeftMenuWidget> {
  List<String> list = ["菜单1", "菜单2", "菜单3"];

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView.separated(
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(
                list[index],
                style: Theme.of(context).textTheme.bodyText1,
              ),
              onTap: () {
                widget.callback.call(index);
              },
            );
          },
          separatorBuilder: (context, index) {
            return Divider();
          },
          itemCount: list.length),
    );
  }
}

class RightMenu extends StatefulWidget {
  final Key key;

  const RightMenu(this.key);

  @override
  _RightMenuState createState() => _RightMenuState();
}

class _RightMenuState extends State<RightMenu> {
  int currentIndex = 0;

  void changePos(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Text("$currentIndex"),
      ),
    );
  }
}
